package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.CommentsApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class CommentsService {
    @DubboReference
    private CommentsApi commentsApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private StringRedisTemplate redisTemplate;
    //查询评论列表
    public PageResult comments(String movementId, Integer page, Integer pagesize) {
        Integer commentType = 2;
        //查询评论
        List<Comment> list = commentsApi.comments(movementId,commentType,page,pagesize);
        if (CollUtil.isEmpty(list)){
            return new PageResult();
        }
        //获取评论人id
        List<Long> ids = CollUtil.getFieldValues(list, "userId", Long.class);
        //查询用户信息
        List<CommentVo> vos = new ArrayList<>();
        Map<Long, UserInfo> map = userInfoApi.findByIds(ids);
        //信息合并
        for (Comment comment : list) {
            UserInfo userInfo = map.get(comment.getUserId());
            CommentVo vo = CommentVo.init(userInfo, comment);
            vos.add(vo);
        }
        return new PageResult(page,pagesize,0l,vos);
    }
    //提交评论
    public void saveComments(String movementId, String comment) {
        Integer commentType = 2;
        Comment comments = new Comment();
        comments.setPublishId(new ObjectId(movementId));
        comments.setCommentType(commentType);
        comments.setContent(comment);
        comments.setUserId(UserHolder.getUserId());
        comments.setCreated(System.currentTimeMillis());
        Integer count = commentsApi.saveComments(comments);
        System.out.println("评论数： " + count);


    }
    //评论- 点赞
    public Integer like(String id) {
        Integer count = commentsApi.addLikeCount(id);
//        //存入redis

//        String redisKey = Constants.MOVEMENTS_INTERACT_KEY + id;
//        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY+UserHolder.getUserId();
//
//        redisTemplate.opsForHash().put(redisKey,hashKey,"1");
        return count;
    }
    //评论 - 取消点赞
    public Integer dislike(String id) {
        Integer count = commentsApi.deleteLikeCount(id);
        return count;

    }
}
